<template>
  <view class="calendar-container" :class="{'new-user': isNewUser}">
    <!-- 左箭头导航按钮，仅在PC端显示 -->
    <view v-if="isPcMode" class="calendar-nav-button calendar-prev-button" @click="navigateDays(-7)">
      <text class="calendar-nav-icon">◀</text>
    </view>
    
    <scroll-view 
      class="calendar-scroll" 
      scroll-x="true" 
      :scroll-into-view="scrollIntoView" 
      scroll-with-animation="true"
      show-scrollbar="false"
      @scroll="handleScroll"
      @mousewheel="handleMouseWheel"
      @wheel="handleMouseWheel"
      enhanced="true">
      <view class="calendar-dates">
        <view v-for="dateItem in calendarDates" :key="dateItem.dateStr" :id="'date-' + dateItem.dateStr" class="date-item" :class="{ 
            'selected': dateItem.dateStr === currentDate,
            'today': dateItem.isToday,
            'other-month': !dateItem.isCurrentMonth
          }" @click="selectDate(dateItem.dateStr)">
          <text class="weekday-text">{{ dateItem.weekday }}</text>
          <text class="date-number">{{ dateItem.isToday ? '今' : dateItem.day }}</text>
        </view>
      </view>
    </scroll-view>
    
    <!-- 右箭头导航按钮，仅在PC端显示 -->
    <view v-if="isPcMode" class="calendar-nav-button calendar-next-button" @click="navigateDays(7)">
      <text class="calendar-nav-icon">▶</text>
    </view>
  </view>
</template>

<script>
export default {
  name: 'DateScrollCalendar',
  props: {
    // 当前选择的日期，格式：YYYY-MM-DD
    value: {
      type: String,
      default: ''
    },
    // 可选择的日期范围（向前天数）
    daysBack: {
      type: Number,
      default: 15
    },
    // 可选择的日期范围（向后天数）
    daysForward: {
      type: Number,
      default: 15
    }
  },
  data() {
    // 获取真实的当前日期，不依赖系统时间
    const getRealDate = () => {
      try {
        const now = new Date();
        // 检查系统日期是否看起来合理（年份在2020-2030之间）
        if (now.getFullYear() < 2020 || now.getFullYear() > 2030) {
          console.warn('系统日期可能不正确:', now);
          // 使用硬编码的合理日期
          return new Date(2023, 6, 16); // 2023年7月16日
        }
        return now;
      } catch (e) {
        console.error('获取日期出错:', e);
        return new Date(2023, 6, 16);
      }
    };
    
    const realDate = getRealDate();
    const formattedDate = this.formatDateString(realDate);
    console.log('日历组件初始化，真实日期:', formattedDate);
    
    return {
      currentDate: this.value || formattedDate,
      calendarDates: [],
      scrollIntoView: '',
      isNewUser: true, // 默认显示滑动提示
      swipeHintTimer: null,
      scrollPosition: 0, // 记录滚动位置
      isDragging: false, // 是否正在拖动
      startX: 0, // 拖动起始位置
      startScrollLeft: 0, // 拖动开始时的滚动位置
      isPcMode: false // 是否为PC模式
    }
  },
  watch: {
    // 监听外部value变化
    value(newVal) {
      if (newVal !== this.currentDate) {
        this.currentDate = newVal;
        this.updateScrollPosition();
      }
    }
  },
  created() {
    this.generateCalendarDates();
  },
  mounted() {
    this.updateScrollPosition();
    
    // 5秒后移除新用户提示
    this.swipeHintTimer = setTimeout(() => {
      this.isNewUser = false;
    }, 5000);
    
    // 添加全局鼠标事件监听
    window.addEventListener('mousemove', this.handleMouseMove);
    window.addEventListener('mouseup', this.handleMouseUp);
    
    // 检测是否为PC模式
    this.detectPcMode();
    // 监听窗口大小变化，重新检测PC模式
    window.addEventListener('resize', this.detectPcMode);
  },
  beforeDestroy() {
    // 清除定时器
    if (this.swipeHintTimer) {
      clearTimeout(this.swipeHintTimer);
    }
    
    // 移除全局鼠标事件监听
    window.removeEventListener('mousemove', this.handleMouseMove);
    window.removeEventListener('mouseup', this.handleMouseUp);
    window.removeEventListener('resize', this.detectPcMode);
  },
  methods: {
    // 格式化日期字符串
    formatDateString(date) {
      try {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
      } catch (e) {
        console.error('格式化日期字符串出错:', e);
        return '2023-07-16'; // 默认日期
      }
    },
    
    // 处理滚动事件，移除新用户提示
    handleScroll(e) {
      if (this.isNewUser) {
        this.isNewUser = false;
      }
      
      // 如果事件对象存在，记录滚动位置
      if (e && e.detail) {
        this.scrollPosition = e.detail.scrollLeft;
      }
    },
    
    // 处理鼠标滚轮事件
    handleMouseWheel(e) {
      // 阻止默认行为，避免页面滚动
      e.preventDefault();
      e.stopPropagation();
      
      // 获取滚轮方向
      const delta = e.deltaY || e.wheelDelta || e.detail;
      
      // 获取scroll-view元素
      const scrollView = this.$el.querySelector('.calendar-scroll');
      if (scrollView) {
        // 计算新的滚动位置
        const scrollAmount = delta > 0 ? 100 : -100;
        scrollView.scrollLeft += scrollAmount;
      }
    },
    
    // 处理鼠标按下事件
    handleMouseDown(e) {
      this.isDragging = true;
      this.startX = e.clientX;
      
      const scrollView = this.$el.querySelector('.calendar-scroll');
      if (scrollView) {
        this.startScrollLeft = scrollView.scrollLeft;
      }
      
      // 阻止默认行为，避免文本选择
      e.preventDefault();
    },
    
    // 处理鼠标移动事件
    handleMouseMove(e) {
      if (!this.isDragging) return;
      
      const x = e.clientX;
      const walk = (this.startX - x) * 1.5; // 乘以系数增加灵敏度
      
      const scrollView = this.$el.querySelector('.calendar-scroll');
      if (scrollView) {
        scrollView.scrollLeft = this.startScrollLeft + walk;
      }
    },
    
    // 处理鼠标释放事件
    handleMouseUp() {
      this.isDragging = false;
    },

    // 格式化日期用于输入
    formatDateForInput(date) {
      try {
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const formattedDate = `${year}-${month}-${day}`;
        console.log('格式化日期:', date, '结果:', formattedDate); // 添加日志
        return formattedDate;
      } catch (error) {
        console.error('日期格式化错误:', error, date);
        // 如果出错，返回当前日期
        const now = new Date();
        return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}-${now.getDate().toString().padStart(2, '0')}`;
      }
    },

    // 更新滚动位置
    updateScrollPosition() {
      this.$nextTick(() => {
        this.scrollIntoView = 'date-' + this.currentDate;
      });
    },

    // 生成日历数据
    generateCalendarDates() {
      try {
        let selectedDate = this.currentDate ? new Date(this.currentDate) : new Date();
        console.log('生成日历数据，选择的日期:', this.currentDate, '解析为:', selectedDate);
        
        // 验证日期是否有效
        if (isNaN(selectedDate.getTime())) {
          console.error('无效的日期:', this.currentDate);
          // 使用默认日期
          selectedDate = new Date(2023, 6, 16); // 2023年7月16日
        }
        
        let today = new Date();
        // 检查系统日期是否看起来合理
        if (today.getFullYear() < 2020 || today.getFullYear() > 2030) {
          console.warn('系统日期可能不正确:', today);
          // 使用硬编码的合理日期作为"今天"
          today = new Date(2023, 6, 16);
        }
        
        const calendarDates = [];
        const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

        // 生成指定范围的日历
        for (let i = -this.daysBack; i <= this.daysForward; i++) {
          const date = new Date(selectedDate);
          date.setDate(selectedDate.getDate() + i);

          const dateStr = this.formatDateString(date);
          const isToday = this.formatDateString(today) === dateStr;
          const isCurrentMonth = date.getMonth() === selectedDate.getMonth();
          const weekday = weekdays[date.getDay()];

          calendarDates.push({
            dateStr: dateStr,
            day: date.getDate(),
            isToday: isToday,
            isCurrentMonth: isCurrentMonth,
            weekday: weekday,
            date: date
          });
        }

        this.calendarDates = calendarDates;
        console.log('生成的日历数据:', calendarDates.map(d => d.dateStr).join(', '));
        this.updateScrollPosition();
      } catch (error) {
        console.error('生成日历数据出错:', error);
      }
    },

    // 选择日期
    selectDate(dateStr) {
      console.log('选择日期:', dateStr); // 添加日志
      this.currentDate = dateStr;
      
      // 发送事件通知父组件
      this.$emit('input', dateStr);
      this.$emit('change', dateStr);
      console.log('发送日期变更事件:', dateStr); // 添加日志

      // 重新生成日历（如果选择的是边界日期）
      const selectedIndex = this.calendarDates.findIndex(
        (item) => item.dateStr === dateStr
      );
      if (
        selectedIndex <= 2 ||
        selectedIndex >= this.calendarDates.length - 3
      ) {
        this.generateCalendarDates();
      }
    },
    
    // 导航指定天数
    navigateDays(days) {
      try {
        // 获取当前选中日期
        const currentDate = new Date(this.currentDate);
        
        // 计算新日期
        currentDate.setDate(currentDate.getDate() + days);
        
        // 格式化为字符串
        const newDateStr = this.formatDateString(currentDate);
        
        // 选择新日期
        this.selectDate(newDateStr);
      } catch (error) {
        console.error('导航日期出错:', error);
      }
    },

    // 检测是否为PC模式
    detectPcMode() {
      // 更严格的PC检测逻辑
      const userAgent = navigator.userAgent.toLowerCase();
      
      // 检测是否为移动设备或平板
      const isMobileOrTablet = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|tablet|silk/i.test(userAgent);
      
      // 检测是否为触摸设备
      const isTouchDevice = ('ontouchstart' in window) || 
                           (navigator.maxTouchPoints > 0) || 
                           (navigator.msMaxTouchPoints > 0);
      
      // 只有在非移动/平板设备且屏幕宽度大于1024px时才认为是PC模式
      this.isPcMode = !isMobileOrTablet && !isTouchDevice && window.innerWidth > 1024;
      
      console.log('设备检测:', { 
        isMobileOrTablet, 
        isTouchDevice, 
        screenWidth: window.innerWidth,
        isPcMode: this.isPcMode 
      });
    }
  }
}
</script>

<style scoped>
/* 滚动日历样式 */
.calendar-container {
  width: 100%;
  background-color: rgba(255, 105, 180, 0.08);
  border-radius: 20rpx;
  padding: 18rpx 0 22rpx;
  border: 1rpx solid rgba(255, 105, 180, 0.15);
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
}

.calendar-scroll {
  width: 100%;
  white-space: nowrap;
  /* 隐藏滚动条但保持可滚动功能 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch; /* 平滑滚动 */
  cursor: grab; /* 显示抓取光标，提示可拖动 */
}

.calendar-scroll:active {
  cursor: grabbing; /* 拖动时显示抓取中光标 */
}

/* 为Webkit浏览器隐藏滚动条 */
.calendar-scroll::-webkit-scrollbar {
  display: none;
  width: 0;
  height: 0;
  background: transparent;
}

/* 通用滚动条隐藏 */
::v-deep ::-webkit-scrollbar {
  display: none !important;
  width: 0 !important;
  height: 0 !important;
  background: transparent !important;
}

.calendar-dates {
  display: inline-flex;
  padding: 0 30rpx;
  gap: 16rpx;
  touch-action: pan-x; /* 明确启用水平滑动触控操作 */
  transition: transform 0.2s ease;
  will-change: transform; /* 优化动画性能 */
}

/* 左右渐变提示，表示可以滚动 */
.calendar-container::before,
.calendar-container::after {
  content: '';
  position: absolute;
  top: 0;
  bottom: 0;
  width: 40rpx;
  z-index: 2;
  pointer-events: none;
}

.calendar-container::before {
  left: 0;
  background: linear-gradient(to right, rgba(28, 29, 48, 0.5), transparent);
  width: 60rpx; /* 增加渐变宽度，提示可滚动 */
}

.calendar-container::after {
  right: 0;
  background: linear-gradient(to left, rgba(28, 29, 48, 0.5), transparent);
  width: 60rpx; /* 增加渐变宽度，提示可滚动 */
}

.date-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 82rpx;
  height: 95rpx;
  border-radius: 16rpx;
  transition: all 0.3s ease;
  flex-shrink: 0;
  cursor: pointer;
  gap: 8rpx;
  position: relative;
  overflow: hidden;
  user-select: none; /* 防止文本选择 */
  -webkit-tap-highlight-color: transparent; /* 移除点击高亮 */
}

.date-item:hover:not(.selected) {
  background: rgba(255, 255, 255, 0.1); /* 鼠标悬停时提供视觉反馈 */
}

.date-item:active {
  transform: scale(0.95);
}

.weekday-text {
  font-size: 22rpx;
  font-weight: 400;
  color: rgba(255, 255, 255, 0.6);
  text-align: center;
  line-height: 1;
}

.date-number {
  font-size: 32rpx;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.9);
  text-align: center;
  line-height: 1;
}

/* 选中状态 */
.date-item.selected {
  background: linear-gradient(135deg, #ff6b9d, #ff8a9b);
  box-shadow: 0 6rpx 20rpx rgba(255, 107, 157, 0.6);
  transform: translateY(-2rpx) scale(1.02);
  border-radius: 16rpx;
}

.date-item.selected .weekday-text,
.date-item.selected .date-number {
  color: white;
  font-weight: 600;
}

/* 今天状态（如果不是选中状态） */
.date-item.today:not(.selected) {
  background: rgba(255, 107, 157, 0.15);
  border: 2rpx solid #ff6b9d;
}

.date-item.today:not(.selected) .weekday-text {
  color: #ff8a9b;
  font-weight: 500;
}

.date-item.today:not(.selected) .date-number {
  color: #ff8a9b;
  font-weight: 600;
}

/* 其他月份的日期 */
.date-item.other-month .weekday-text,
.date-item.other-month .date-number {
  color: rgba(255, 255, 255, 0.3);
}

/* 默认状态 */
.date-item:not(.selected):not(.today) {
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(2px);
  border: 1rpx solid rgba(255, 255, 255, 0.08);
}

/* 移除滑动指示动画 */
.calendar-container.new-user::after {
  opacity: 0.8; /* 增强可见性 */
}

/* 导航按钮样式 */
.calendar-nav-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 40rpx;
  height: 40rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(255, 107, 157, 0.1);
  border-radius: 4rpx;
  z-index: 10;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1rpx solid rgba(255, 255, 255, 0.1);
}

.calendar-nav-button:hover {
  background: rgba(255, 107, 157, 0.3);
}

.calendar-nav-button:active {
  transform: translateY(-50%) scale(0.95);
}

.calendar-prev-button {
  left: 2rpx;
}

.calendar-next-button {
  right: 2rpx;
}

.calendar-nav-icon {
  color: rgba(255, 255, 255, 0.7);
  font-size: 16rpx;
  line-height: 1;
}

/* 调整滚动区域宽度，为按钮留出空间 */
.calendar-scroll {
  width: calc(100% - 50rpx);
  margin: 0 auto;
}
</style> 